<template>
  <div class="mod-config">
    <el-card class="box-card search-input" shadow="never">
      <el-form  label-width="120px"  size="mini" :model="dataForm" @keyup.enter.native="findPage()">
        <el-row>
          <el-col :span="6">
            <el-form-item label="话题名称：">
              <el-input v-model="dataForm.name" ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建日期：">
              <el-date-picker
                @change="createTimeChange"
                style="width: 100%"
                v-model="createTime"
                value-format="yyyy-MM-dd HH:mm:ss"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="状态：">
              <cy-select url="/api/v1/broadcast/config/banner_info_status/val" :all-option="true" v-model="dataForm.status"></cy-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24" style="text-align: center;">
            <el-form-item>
              <el-button type="primary" @click="$refs.CyTable.query(dataForm)">查询</el-button>
              <el-button @click="reset()">重置</el-button>
              <el-button type="primary" @click="showEdit">新增话题</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>
    <live-banner-info-list-table
      url="/api/v1/liveBannerInfo/list"
      :max-height="600"
      :showBatchDelete="false"
      :showSelection="false"
      :highlightCurrentRow="true"
      :operationWidth="300"
      :content="pageResult"
      :totalSize="totalSize"
      :columns="filterColumns"
      :showEditOperation="true"
      :showDeleteOperation="true"
      @handleDelete="handleDelete"
      @findPage="findPage"
      @handleEdit="handleEdit"
      ref="CyTable"
    >
    </live-banner-info-list-table>
    <el-dialog
      width="50%"
      :title="operationText"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      @close="editCancel">
      <el-row v-loading="addLoading">
        <el-form  label-width="120px" ref="editDataForm" size="mini" :rules="rules" :model="editDataForm">
          <el-col :span="24">
            <el-form-item label="banner名称：" prop="name">
              <el-input :disabled="isDisabledEdit" maxlength="20" placeholder="最多可编辑20个字" v-model="editDataForm.name" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="封面：" prop="pic">
              <cy-file-upload
                :disabled="isDisabledEdit"
                :customStyle="fileStyle"
                :before-upload="beforeAvatarUpload"
                v-model="editDataForm.pic"
                @onSuccess="fileUploadSuccess"
              ></cy-file-upload>
              <div>封面图片请上传尺寸为600px*600px的图片</div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="跳转链接：" prop="type">
              <el-radio-group :disabled="isDisabledEdit" v-model="editDataForm.type">
                <el-radio :label="0">URL</el-radio>
                <el-radio :label="1">APP_CMS_ID</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="" prop="url">
              <el-input :disabled="isDisabledEdit" v-model="editDataForm.url" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10" offset="8">
            <el-button size="mini" v-if="!isDisabledEdit" @click="editCancel">取消</el-button>
            <el-button size="mini" v-if="!isDisabledEdit" type="primary" @click="dataFormSubmit('editDataForm')">确定</el-button>
          </el-col>
        </el-form>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
  import CySelect from "./component/CySelect";
  import CyFileUpload from "./component/CyFileUpload";
  import LiveBannerInfoListTable from "./component/LiveBannerInfoListTable";
  export default {
    components: {
      CySelect,
      CyFileUpload,
      LiveBannerInfoListTable,
    },
    data() {
      return {
        loading: false,
        addLoading: false,
        moreBtnDisable: true,
        createTime: [],
        time: [],
        dataForm: {},
        editDataForm: {
          type: 0,
          pic: '',
          name:'',
          url:''
        },
        imageAddBtn:{
          width: '180px',
          height: '120px',
          marginBottom: '10px'
        },
        fileStyle:{
          width: '200px',
          height: '200px',
          marginBottom: '10px'
        },
        columns: [],
        filterColumns: [],
        bannerList:[],
        pageRequest: {pageNum: 1, pageSize: 10},
        pageResult: [],
        totalSize: 0,
        operationText: '新增banner',
        dialogVisible: false, // 新增编辑界面是否显示
        editLoading: false,
        isDisabledEdit: true,
        countNumForm: {
          allShopNum: '',
          onlineNum: '',
          offlineNum: ''
        },
        dataList: [],
        pageIndex: 1,
        pageSize: 10,
        totalPage: 0,
        dataListLoading: false,
        dataListSelections: [],
        invoiceUpdateVisible: true,
        rules: {
          name: [
            { required: true, message: '请填写banner名称', trigger: 'blur' }
          ],
          type: [
            { required: true, message: '请选择跳转类型', trigger: 'change' }
          ],
          url: [
            { required: true, message: '请填写跳转地址', trigger: 'blur' },
            {
              validator:this.verify,
              trigger: 'blur',
            }
          ],
          pic: [
            { required: true, message: '请选择封面', trigger: 'blur' }
          ]
        },
      }
    },
    mounted: function () {
      this.columns = [
        {prop: "id", label: "队列编号", minWidth: 120},
        {prop: "pic", label: "封面", minWidth: 120, showType:'image',imgSize:{width:100,height:100}},
        {prop: "name", label: "名称", minWidth: 120},
        {prop: "url", label: "跳转链接", minWidth: 180},
        {prop: "releaseTime", label: "发布日期", minWidth: 180},
        {prop: "createTime", label: "创建日期", minWidth: 180},
        {prop: "status", label: "状态", minWidth: 120,formatter:function (row, column, cellValue, index) {
            if (cellValue == 30) {
              return "未发布";
            } else if (cellValue == 31) {
              return "已发布";
            } else if (cellValue == 32) {
              return "待发布";
            }
            return "";
          }}
      ];
      let temp = [];
      this.columns.forEach(function (key, val) {
        temp.push(key);
      });
      this.filterColumns = temp;
    },
    methods: {
      verify(rule, value, callback){
        if(this.editDataForm.type==0) {
          if (!/^http(s)?:\/\/([\w-]+\.)+[\w-]+(\/[\w- ./?%&=]*)?$/.test(value)) {
            callback(new Error('格式不正确 ( http[s]://www.xxx '));
          }else{
            callback();
          }
        }else{
          callback();
        }
      },
      // 获取数据列表
      findPage() {
        this.$refs.CyTable.findPage(this.dataForm);
      },
      //重置
      reset() {
        this.dataForm = {};
        this.$refs.CyTable.resetForm(this.dataForm);
      },
      // 显示编辑界面
      handleEdit: function (params) {
        this.dialogVisible = true;
        if(params.type == 'edit'){
          this.operationText = '编辑banner';
          this.isDisabledEdit = false
        } else if(params.type == 'detail'){
          this.operationText = '查看banner';
          this.isDisabledEdit = true
        }
        this.editDataForm = params.row;
      },
      showEdit(){
        this.operationText = '新增banner';
        this.dialogVisible = true;
        this.isDisabledEdit = false
      },
      // 删除
      handleDelete: function (params) {
        let ids = params.params;
        let delDataForm = [];
        ids.forEach(val=>{
          delDataForm.push(val)
        })
        if(delDataForm.length>0){
          let this_ = this;
          this.utils.request.liveRequest({
            url: '/api/v1/liveBannerInfo/batchDelete',
            method: 'post',
            params: delDataForm
          }).then(result => {
            let data = result.data;
            if (data.code === '0') {
              this_.$refs.CyTable.findPage(this_.dataForm)
              this_.$forceUpdate();
              this.$message({message: "操作成功", type: "success"});
            }
          })
        } else {
          this.$message({message: "请选择需要删除的数据", type: "error"});
        }

      },
      // 创建日期改变
      createTimeChange: function (val) {
        if (val) {
          this.dataForm.createTimeStart = val[0]
          this.dataForm.createTimeEnd = val[1]
        } else {
          this.dataForm.createTimeStart = ''
          this.dataForm.createTimeEnd = ''
        }
      },
      // 生效日期改变
      timeChange: function (val) {
        if (val) {
          this.dataForm.timeStart = val[0]
          this.dataForm.timeEnd = val[1]
        } else {
          this.dataForm.timeStart = ''
          this.dataForm.timeEnd = ''
        }
      },
      // 编辑取消
      editCancel(){
        this.dialogVisible = false
        this.editDataForm = {
          type: 0,
          pic: '',
          name:'',
          url:''
        }
        this.$refs.editDataForm.resetFields();
      },
      // 新增提交
      dataFormSubmit(formName){
        let this_ = this;
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.$confirm("确认提交吗？", "提示", {}).then(() => {
              this.addLoading=true;
              this.utils.request.liveRequest({
                url: '/api/v1/liveBannerInfo/save',
                method: 'Post',
                params: this.editDataForm
              }).then(result => {
                this_.editCancel();
                let data = result.data;
                if (data.code === '0') {
                  this_.$refs.CyTable.findPage(this_.dataForm)
                  this_.$forceUpdate();
                  this.$message({message: "操作成功", type: "success"});
                }
                this.addLoading=false;
              })
            })
          } else {
            return false;
          }
        });
      },
      fileUploadSuccess(res, file) {
        this.editDataForm.pic = res.data;
      },
      beforeAvatarUpload(file) {
        // 限制图片大小
        const isSize = new Promise((resolve,reject)=> {
          let width = 600;
          let height = 600;
          let _URL = window.URL || window.webkitURL;
          let img = new Image();
          img.src = _URL.createObjectURL(file)
          img.onload = function() {
            let valid = img.width == width && img.height == height
            valid ? resolve() : reject();
          }
        })
          .then(()=>{
            return file;
          },()=>{
            this.$message.error('上传图片像素格式为600*600!');
            return Promise.reject();
          })
        return isSize;
      }
    }
  }
</script>
<style scoped lang="scss">

</style>
